{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用cookie绕过登录验证\n",
    "- 安装chrome浏览器插件EditThisCookie\n",
    "- 登录网页后点击该插件，并导出cookies到记事本.txt备用\n",
    "- 使用requests带上cookies请求网页"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 核心部分\n",
    "- 实例化对象名为cookie_jar\n",
    "- 读取记录cookie内容的记事本，并序列化\n",
    "- 设置对象的相关内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "cookie_jar = requests.cookies.RequestsCookieJar()\n",
    "with open('cookies.txt') as fin:\n",
    "    cookieJson = json.load(fin)\n",
    "    for cookie in cookieJson:\n",
    "        cookie_jar.set(\n",
    "            name = cookie['name'],\n",
    "            value = cookie['value'],\n",
    "            domain = cookie['domain'],\n",
    "            path = cookie['path'],\n",
    "        )\n",
    "\n",
    "# 也可以将cookie_jar转换为cookie字典\n",
    "# cookies_dic = requests.utils.dict_from_cookiejar(cookie_jar)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 带上cookies请求网页"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = 'https://wwww.baidu.com'\n",
    "headers={'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'}\n",
    "response = requests.get(url, headers=headers, cookies=cookie_jar)\n",
    "response.text"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "efbf56fc117e418e44edda1cb10ef72e1d236bfeb453c90c79d8abd3fc7dd926"
  },
  "kernelspec": {
   "display_name": "Python 3.8.8 64-bit ('venv0': venv)",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
